package cuit.epoch.pymjl.distribuitedlock.service.impl;

import cuit.epoch.pymjl.distribuitedlock.entity.Warehouse;
import cuit.epoch.pymjl.distribuitedlock.factory.DistributedLockClient;
import cuit.epoch.pymjl.distribuitedlock.lock.DistributedRedisLock;
import cuit.epoch.pymjl.distribuitedlock.mapper.WarehouseMapper;
import cuit.epoch.pymjl.distribuitedlock.service.WarehouseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Pymjl
 * @since 2022-10-10
 */
@Service
public class WarehouseServiceImpl extends ServiceImpl<WarehouseMapper, Warehouse> implements WarehouseService {
    ReentrantLock lock = new ReentrantLock();
    @Resource
    DistributedLockClient distributedLockClient;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public String deduct() {
        lock.lock();
        try {
            Warehouse warehouse = baseMapper.selectById(1);
            int cnt = 0;
            if (warehouse != null && warehouse.getCount() > 0) {
                cnt = warehouse.getCount();
                warehouse.setCount(cnt - 1);
                baseMapper.updateById(warehouse);
                return "剩余的库存数量：" + (cnt - 1);
            } else {
                return "已经没有库存啦~";
            }
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void deductInRedis() {
        DistributedRedisLock redisLock = this.distributedLockClient.getRedisLock("lock");
        redisLock.lock();

        try {
            // 1. 查询库存信息
            String stock = Objects.requireNonNull(stringRedisTemplate.opsForValue().get("stock"));

            // 2. 判断库存是否充足
            if (stock != null && stock.length() != 0) {
                Integer st = Integer.valueOf(stock);
                if (st > 0) {
                    // 3.扣减库存
                    stringRedisTemplate.opsForValue().set("stock", String.valueOf(--st));
                }
            }
            TimeUnit.SECONDS.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            redisLock.unlock();
        }
    }

    public void test() {

    }
}
